package org.finesys.common.tenant.filter;

import org.finesys.common.security.core.util.SecurityUtils;
import org.finesys.common.tenant.support.TenantContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 多租户上下文过滤器
 */
public class TenantContextWebFilter extends OncePerRequestFilter {

    /**
     * 保存租户信息到上下文
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        // 获取请求携带的租户id
        Long tenantId = SecurityUtils.getTenantId(request);
        if (Objects.nonNull(tenantId)) {
            // 保存租户id到上下文
            TenantContextHolder.setTenantId(tenantId);
        }
        try {
            filterChain.doFilter(request, response);
        } finally {
            // 清理
            TenantContextHolder.clear();
        }
    }
}
